package com.gk.panda.apis.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import com.gk.panda.apis.Vo.RealtimeShootListVo;
import com.gk.panda.apis.Vo.RealtimeShootVo;
import com.gk.panda.apis.client.ChenCameraClient;
import com.gk.panda.apis.config.IccConfig;
import com.gk.panda.apis.dto.*;
import com.gk.panda.apis.entity.eventtodo.dto.AcceptanceEventDto;
import com.gk.panda.apis.entity.eventtodo.dto.SaveEventTodoDto;
import com.gk.panda.apis.entity.icc.dto.CameraDto;
import com.gk.panda.apis.entity.icc.vo.IccMapResultVo;
import com.gk.panda.apis.entity.icc.vo.VideoListResultInfo;
import com.gk.panda.apis.entity.icc.vo.VideoListVo;
import com.gk.panda.apis.enums.EventFlowRecordStatusEnum;
import com.gk.panda.apis.enums.EventToDoStatusEnum;
import com.gk.panda.apis.mapper.RealtimeShootMapper;
import com.gk.panda.apis.patrol.servicr.ReportResourceService;
import com.gk.panda.apis.service.*;
import com.gk.panda.commons.constant.Constants;
import com.gk.panda.commons.exception.ServerException;
import com.gk.panda.commons.result.Result;
import com.gk.panda.commons.util.UserUtil;
import com.gk.panda.pojo.*;
import com.gk.panda.pojo.client.ShotLogListDTO;
import com.gk.panda.pojo.patrol.entity.ReportResourceEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class RealtimeShootServiceImpl extends ServiceImpl<RealtimeShootMapper, RealtimeShoot> implements RealtimeShootService {

    @Autowired
    private IccConfig iccConfig;

    @Autowired
    private DeviceManagerService deviceManagerService;

    @Autowired
    private IClient iClient;

    @Autowired
    private BiodiversityService biodiversityService;

    @Autowired
    private BiologyFileService biologyFileService;

    @Autowired
    private EventTodoService eventTodoService;

    @Autowired
    private EventResourcesService eventResourcesService;

    @Autowired
    private EventFlowRecordService eventFlowRecordService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private FdfsService fdfsService;

    @Autowired
    private ReportResourceService reportResourceService;

    @Autowired
    private BiologyPointService biologyPointService;

    @Autowired
    private ChenCameraClient chenCameraClient;

    /**
     * 分页查询实时抓拍列表
     *
     * @param dto
     * @return
     * @throws ClientException
     */
    @Override
    public Page<RealtimeShootListVo> getRealTimeShootPage(RealtimeShootListDto dto) throws ClientException {
        QueryWrapper<RealtimeShoot> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getSearchParam())) {
            wrapper.and(queryWrapper -> {
                queryWrapper.like("place", dto.getSearchParam()).or()
                        .like("device_name", dto.getSearchParam()).or()
                        .like("device_sn", dto.getSearchParam());
            });
        }
        if (dto.getOrgIds() != null) {
            wrapper.in("org_id", dto.getOrgIds());
        }
        wrapper.eq(StringUtils.isNotEmpty(dto.getDeviceSn()), "device_sn", dto.getDeviceSn());
        wrapper.gt(dto.getStartTime() != null, "get_time", dto.getStartTime());
        wrapper.lt(dto.getEndTime() != null, "get_time", dto.getEndTime());
        wrapper.in(!CollectionUtils.isEmpty(dto.getFileStatus()), "file_status", dto.getFileStatus());
        wrapper.orderByDesc("get_time");
        List<RealtimeShoot> realtimeShoots = this.list(wrapper);
        //当前页
        int current = dto.getPageNumber();
        //每页数据条数
        int size = dto.getPageSize();
        Page<RealtimeShootListVo> page = new Page<>(current, size);
        int count = realtimeShoots.size();
        List<RealtimeShootListVo> pageList = new ArrayList<>();
        //计算当前页第一条数据的下标
        int currId = current > 1 ? (current - 1) * size : 0;
        for (int i = 0; i < size && i < count - currId; i++) {
            pageList.add(convert(realtimeShoots.get(currId + i)));
        }
        page.setSize(size);
        page.setCurrent(current);
        page.setTotal(count);
        //计算分页总页数
        page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
        page.setRecords(pageList);
        return page;
    }

    /**
     * 转换
     * @param realtimeShoot
     * @return
     */
    private RealtimeShootListVo convert(RealtimeShoot realtimeShoot) {
        RealtimeShootListVo vo = new RealtimeShootListVo();
        List<RealtimeShootVo> list = new ArrayList<>();
        RealtimeShootVo shootVo = new RealtimeShootVo();
        BeanUtils.copyProperties(realtimeShoot, shootVo);
        //已归档的实时抓拍查询关联字段
        if (realtimeShoot.getFileStatus() == 1) {
            if (realtimeShoot.getFileType() == 0) {//动植物归档
                String fileId = realtimeShoot.getFileRelation();
                BiologyFile biologyFile = biologyFileService.getById(fileId);
                shootVo.setBehavior(biologyFile.getBehavior());
                shootVo.setName(biologyFile.getBiologyName());
                shootVo.setNum(biologyFile.getBiologyNum());
                Biodiversity biodiversity = biodiversityService.getOne(Wrappers.<Biodiversity>lambdaQuery().eq(Biodiversity::getSpecies, biologyFile.getBiologyName()));
                shootVo.setIntroduce(biodiversity.getIntroduce());
                shootVo.setBiologyNum(biodiversity.getNumber());
            } else if (realtimeShoot.getFileType() == 1) {//事件归档
                String eventId = realtimeShoot.getFileRelation();
                EventTodo eventTodo = eventTodoService.getById(eventId);
                shootVo.setEventTitle(eventTodo.getEventTitle());
                shootVo.setEventStatus(eventTodo.getEventStatus());
                shootVo.setEventNum(eventTodo.getEventSn());
                shootVo.setEventDescription(eventTodo.getEventDescription());
                shootVo.setAcceptor(eventTodo.getFkUpdate());
            }
        }
        list.add(shootVo);
        vo.setRealtimeShootVos(list);
        return vo;
    }

    /**
     * 添加实时抓拍
     *
     * @param dto
     * @return
     */
    @Override
    public boolean addRealTimeShoot(RealtimeShootSaveDto dto) {
        RealtimeShoot realtimeShoot = new RealtimeShoot();
        BeanUtils.copyProperties(dto, realtimeShoot);
        return this.save(realtimeShoot);
    }

    /**
     * 保存Icc抓拍图片视频信息
     */
    @Override
    public void saveIccVideoAndPic() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date end = new Date();
        Date start = new Date(end.getTime() - 600000);
        String endTime = df.format(end);
        String startTime = df.format(start);
        List<VideoListVo> videoListVos = new ArrayList<>();
        CameraDto cameraDto = new CameraDto();
        cameraDto.setPageNum(1);
        cameraDto.setPageSize(20);
        cameraDto.setStartAlarmTime(startTime);
        cameraDto.setEndAlarmTime(endTime);
        List<DeviceManager> devices = deviceManagerService.getIccDeviceSn();
        try {
            String url = iccConfig.getCameraVideoAndPicUrl();
            List<RealtimeShoot> realtimeShoots = new ArrayList<>();
            for (DeviceManager device : devices) {
                cameraDto.setDeviceCode(device.getDeviceSn());
                GeneralRequest generalRequest = new GeneralRequest(url, Method.POST);
                generalRequest.body(JSON.toJSONString(cameraDto));
                GeneralResponse response = iClient.doAction(generalRequest, generalRequest.getResponseClass());
                IccMapResultVo iccMapResultVo = JSON.parseObject(response.getResult(), IccMapResultVo.class);
                String token = iClient.getAccessToken().getAccess_token();
                if (iccMapResultVo.getSuccess()) {
                    VideoListResultInfo info = JSON.parseObject(iccMapResultVo.getData(), VideoListResultInfo.class);
                    videoListVos = info.getPageList();
                }
                if (videoListVos.size() > 0) {
                    for (VideoListVo videoListVo : videoListVos) {
                        RealtimeShoot realtimeShoot = new RealtimeShoot();
                        realtimeShoot.setDeviceName(videoListVo.getCameraName());
                        realtimeShoot.setDeviceSn(videoListVo.getDeviceId());
                        realtimeShoot.setGetTime(videoListVo.getAlarmTime() == null ? new Date() : videoListVo.getAlarmTime());
                        realtimeShoot.setEvent(videoListVo.getAlarmTypeName());
                        if (videoListVo.getPicUrl() != null) {
                            String str = "https://" + iccConfig.getHost() + "/evo-apigw/evo-oss/" + videoListVo.getPicUrl() + "?token=" + token;
                            String path = fdfsService.updateFromIcc(str);
                            realtimeShoot.setPath(path);
                        } else if (videoListVo.getVideoUrl() != null) {
                            String str = "https://" + iccConfig.getHost() + "/evo-apigw/evo-oss/" + videoListVo.getVideoUrl() + "?token=" + token;
                            String path = fdfsService.updateFromIcc(str);
                            realtimeShoot.setPath(path);
                        } else continue;
                        realtimeShoot.setPlace(device.getDeviceAddress());
                        realtimeShoot.setLot(videoListVo.getLongitude());
                        realtimeShoot.setLat(videoListVo.getLatitude());
                        realtimeShoot.setSource(1);
                        realtimeShoot.setOrgId(device.getFkOrgId());
                        realtimeShoots.add(realtimeShoot);
                    }
                    VideoListVo videoListVo = videoListVos.get(videoListVos.size() - 1);
                    String power = videoListVo.getPower();
                    device.setRemainingElectricity(power);
                    deviceManagerService.updatePower(device);
                    //电量低于30%生成事件
                    if (Integer.parseInt(power.replace("%", "")) < 30) {
                        eventTodoService.saveBatteryEvent(device);
                    }
                }

            }
            saveBatch(realtimeShoots);

        } catch (Exception e) {
            throw new ServerException("调用ICC获取野保相机图片视频列表接口失败");
        }
    }

    /**
     * 实时抓拍归档
     *
     * @param dto
     * @return
     * @throws UnsupportedEncodingException
     */
    @Override
    @Transactional
    public int filePicAndVideo(RealtimeShootFileDto dto) throws UnsupportedEncodingException {
        String user = UserUtil.getCurrentUser();
        String name = UserUtil.getCurrentUserName();
        if (StringUtils.isEmpty(dto.getPicId()) && StringUtils.isEmpty(dto.getVideoId())) {
            throw new ServerException("文件不能为空");
        }
        //如果包含已归档的图片视频，则先将之前的归档删除
        checkFile(dto);

        Integer fileType = dto.getFileType();
        //动植物归档
        if (fileType == 0) {
            //查询生物名录是否有此物种
            String species = dto.getSpecies();
            Biodiversity biodiversity = biodiversityService.getBaseMapper().selectOne(Wrappers.<Biodiversity>lambdaQuery().eq(Biodiversity::getSpecies, species));
            if (biodiversity == null) {//如果没有就添加新物种到生物名录
                BiodiversitySaveDto saveDto = new BiodiversitySaveDto();
                BeanUtils.copyProperties(dto, saveDto);
                if (StringUtils.isNotEmpty(dto.getPicId())) {
                    saveDto.setPictureUrl(getById((dto.getPicId().split(","))[0]).getPath());
                }
                saveDto.setDataSource(1);
                biodiversityService.addBiodiversity(saveDto);
            } else {//如果有此物种则检查是否需要更新数据到生物名录
                BeanUtils.copyProperties(dto, biodiversity);
                biodiversityService.updateById(biodiversity);
            }
            Date findTime = new Date(1000);
            //动植物图片
            if (StringUtils.isNotEmpty(dto.getPicId())) {
                String[] ids = dto.getPicId().split(",");
                List<RealtimeShoot> realtimeShoots = listByIds(Arrays.asList(ids));
                for (RealtimeShoot realtimeShoot : realtimeShoots) {
                    findTime = realtimeShoot.getGetTime().getTime() > findTime.getTime() ? realtimeShoot.getGetTime() : findTime;
                    biologyFile(realtimeShoot, dto, 0);//type:0-图片1-视频
                }
                point(biodiversity,realtimeShoots,dto);//动植物点位打点

            }
            //动植物视频
            if (StringUtils.isNotEmpty(dto.getVideoId())) {
                String[] ids = dto.getVideoId().split(",");
                List<RealtimeShoot> realtimeShoots = listByIds(Arrays.asList(ids));
                for (RealtimeShoot realtimeShoot : realtimeShoots) {
                    findTime = realtimeShoot.getGetTime().getTime() > findTime.getTime() ? realtimeShoot.getGetTime() : findTime;
                    biologyFile(realtimeShoot, dto, 1);//type:0-图片1-视频
                }
            }
            //更新动植物最新发现时间
//            Biodiversity one = biodiversityService.getOne(Wrappers.<Biodiversity>lambdaQuery().eq(Biodiversity::getSpecies, dto.getSpecies()));
            if (biodiversity != null && (biodiversity.getFindTime() == null || findTime.getTime() > biodiversity.getFindTime().getTime())) {
                biodiversityService.update(Wrappers.<Biodiversity>lambdaUpdate().eq(Biodiversity::getSpecies, dto.getSpecies()).set(Biodiversity::getFindTime, findTime));
            }
            //事件归档
        } else if (fileType == 1) {
            SaveEventTodoDto saveDto = new SaveEventTodoDto();
            BeanUtils.copyProperties(dto, saveDto);
            saveDto.setCreateName(name);
            saveDto.setFkCreate(user);
            saveDto.setOrgName(orgService.getById(dto.getOrgId()).getName());
            if (dto.getNeedDispose() == 1) {//不需要处置直接完成
                saveDto.setEventStatus(EventToDoStatusEnum.PROCESSING_COMPLETED.getCode());
                saveDto.setFkUpdate(user);
                saveDto.setUpdateName(name);
                saveDto.setFinishTime(new Date());
            }
            int eventId = eventTodoService.saveEventTodoInfo(saveDto);
            if (dto.getNeedDispose() == 1) {//不需要处置的事件归档后保存流转记录
                //保存流转记录
                AcceptanceEventDto eventDto = new AcceptanceEventDto();
                eventDto.setEventId(eventId);
                eventDto.setFkRecipient(user);
                eventDto.setRecipientName(name);
                eventFlowRecordService.saveRecordByStatus(eventDto, EventFlowRecordStatusEnum.PROCESSING_COMPLETED.getCode(), Constants.COMPLETED);
            }
            //保存事件图片视频资源
            List<EventResources> list = new ArrayList<>();
            if (StringUtils.isNotEmpty(dto.getPicId())) {
                String[] ids = dto.getPicId().split(",");
                List<RealtimeShoot> realtimeShoots = listByIds(Arrays.asList(ids));
                for (RealtimeShoot realtimeShoot : realtimeShoots) {
                    EventResources eventResources = new EventResources();
                    eventResources.setCreateName(name);
                    eventResources.setCreateTime(new Date());
                    eventResources.setFileType(1);
                    eventResources.setFileUrl(realtimeShoot.getPath());
                    eventResources.setFkCreate(user);
                    eventResources.setEventId(eventId);
                    list.add(eventResources);
                    //更新实时抓拍归档关联字段
                    realtimeShoot.setFileType(1);
                    realtimeShoot.setFileStatus(1);
                    realtimeShoot.setFileRelation(Integer.toString(eventId));
                    updateById(realtimeShoot);
                }
            }
            if (StringUtils.isNotEmpty(dto.getVideoId())) {
                String[] ids = dto.getVideoId().split(",");
                List<RealtimeShoot> realtimeShoots = listByIds(Arrays.asList(ids));
                for (RealtimeShoot realtimeShoot : realtimeShoots) {
                    EventResources eventResources = new EventResources();
                    eventResources.setCreateName(name);
                    eventResources.setCreateTime(new Date());
                    eventResources.setFileType(2);
                    eventResources.setFileUrl(realtimeShoot.getPath());
                    eventResources.setFkCreate(user);
                    eventResources.setEventId(eventId);
                    list.add(eventResources);
                    //更新实时抓拍归档关联字段
                    realtimeShoot.setFileType(1);
                    realtimeShoot.setFileStatus(1);
                    realtimeShoot.setFileRelation(Integer.toString(eventId));
                    updateById(realtimeShoot);
                }
            }
            eventResourcesService.saveResourceList(list);
        }
        return 0;
    }

    /**
     * 动植物点位打点
     * @param biodiversity
     * @param realtimeShoots
     * @param dto
     */
    private void point(Biodiversity biodiversity, List<RealtimeShoot> realtimeShoots, RealtimeShootFileDto dto) {
        List<String[]> list = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        for (RealtimeShoot shoot : realtimeShoots) {
            String lot;//经度
            String lat;//纬度
            if (shoot.getSource() == 1) {
                lot = shoot.getLot().replace("东经","");
                lat = shoot.getLat().replace("北纬","");
            } else {
                lot = shoot.getLot();
                lat = shoot.getLat();
            }
            String s = "[" + lot + "," + lat + "]";
            if (!sb.toString().contains(s)) {
                sb.append(s).append("|");
                String[] strs = new String[]{lot,lat};
                list.add(strs);
            }
        }
        List<String[]> place = list.stream().distinct().collect(Collectors.toList());
        //查看此物种点位
        BiologyPoint one = biologyPointService.getOne(Wrappers.<BiologyPoint>lambdaQuery().eq(BiologyPoint::getName, dto.getSpecies()));

        //存在此物种点位，则在原来的基础上增加打点
        if (one != null) {
            String json = one.getGeoJson();
            for (String[] point : place) {
                String lot = point[0];//经度
                String lat = point[1];//纬度
                String str = "[" + lot + "," + lat + "]";
                if (!json.contains(str)) {
                    String[] split = json.split("]}");
                    json = split[0] + "," + str +"]}" + split[1];
                }
            }
            biologyPointService.update(Wrappers.<BiologyPoint>lambdaUpdate().eq(BiologyPoint::getId,one.getId())
                    .set(BiologyPoint::getGeoJson,json));
        } else {//不存在此物种点位，新建一个点位
            BiologyPointSaveDto saveDto = new BiologyPointSaveDto();
            saveDto.setBioId(biodiversity.getId());
            saveDto.setKingdom(biodiversity.getKingdom());
            saveDto.setName(biodiversity.getSpecies());
            saveDto.setPicUrl(realtimeShoots.get(0).getPath());
            saveDto.setBioId(biodiversity.getId());
            saveDto.setPlace(place);
            //新增
            biologyPointService.addBiologyPoint(saveDto);
        }
    }

    /**
     * 删除已归档的实时抓拍
     *
     * @param dto
     */
    private void checkFile(RealtimeShootFileDto dto) {
        List<String> realtimeShootIds = new ArrayList<>();
        if (dto.getPicId() != null) realtimeShootIds.addAll(Arrays.asList(dto.getPicId().split(",")));
        if (dto.getVideoId() != null) realtimeShootIds.addAll(Arrays.asList(dto.getVideoId().split(",")));
        List<RealtimeShoot> shoots = list(Wrappers.<RealtimeShoot>lambdaQuery().in(RealtimeShoot::getId, realtimeShootIds));
        shoots.forEach(realtimeShoot -> {
            if (realtimeShoot.getFileStatus() == 1) {
                String relation = realtimeShoot.getFileRelation();
                if (realtimeShoot.getFileType() == 0) {
                    biologyFileService.removeById(relation);
                } else {
                    eventResourcesService.remove(Wrappers.<EventResources>lambdaQuery().eq(EventResources::getEventId, relation));
                }
            }
        });
    }

    /**
     * 根据实时抓拍id获取抓拍图片视频地址
     *
     * @param id
     * @return
     */
    @Override
    public List<RealtimeShoot> getPicPathById(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new ServerException("id不能为空");
        }
        String[] ids = id.split(",");
        QueryWrapper<RealtimeShoot> wrapper = new QueryWrapper<>();
        wrapper.select("id", "path").in("id", Arrays.asList(ids));
        List<RealtimeShoot> shoots = list(wrapper);
        return shoots;
    }

    /**
     * 根据id删除实时抓拍
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> delById(String id) {
        String[] ids = id.split(",");
        List<RealtimeShoot> realtimeShoots = listByIds(Arrays.asList(ids));
        boolean remove = removeByIds(Arrays.asList(ids));
        if (remove) {
            for (RealtimeShoot realtimeShoot : realtimeShoots) {
                if (realtimeShoot.getFileStatus() != 1 && realtimeShoot.getSource() != 0 && realtimeShoot.getPath() != null) {
                    try {
                        reportResourceService.update(Wrappers.<ReportResourceEntity>lambdaUpdate().eq(ReportResourceEntity::getUrl, realtimeShoot.getPath()).set(ReportResourceEntity::getDelFlag, 1));
                        fdfsService.deleteFile(realtimeShoot.getPath());
                    } catch (Exception e) {
                        return Result.write(200, "删除成功");
                    }
                }
            }
        }

        if (!remove) return Result.write(201, "删除失败");
        return Result.write(200, "删除成功");
    }

    /**
     * 挂起实时抓拍，暂不归档
     *
     * @param realtimeShootIds
     */
    @Override
    public void withholdFile(String realtimeShootIds) {
        if (StringUtils.isEmpty(realtimeShootIds)) {
            throw new ServerException("未选择文件");
        }
        List<String> ids = Arrays.asList(realtimeShootIds.split(","));
        update(Wrappers.<RealtimeShoot>lambdaUpdate().set(RealtimeShoot::getFileStatus, 2).in(RealtimeShoot::getId, ids));
    }

    @Override
    public void saveChenVideoAndPic(String startTime, String endTime) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<DeviceManager> deviceList = deviceManagerService.getChenDeviceSn();
        Map<String, DeviceManager> collect = deviceList.stream().collect(Collectors.toMap(DeviceManager::getDeviceSn, Function.identity(), (k1,k2) -> k1));
        ShotLogListDTO shotLogListDTO = new ShotLogListDTO();
        shotLogListDTO.setStartTime(df.parse(startTime));
        shotLogListDTO.setEndTime(df.parse(endTime));
        List<ChenCameraShotLog> chenCameraShotLogs = chenCameraClient.listByDeviceId(shotLogListDTO);
        Map<String, List<ChenCameraShotLog>> shotMap = chenCameraShotLogs.stream().collect(Collectors.groupingBy(ChenCameraShotLog::getId));
        List<RealtimeShoot> realtimeShoots = new ArrayList<>();
        for (Map.Entry<String, DeviceManager> entry : collect.entrySet()) {
            String deviceSn = entry.getKey();
            DeviceManager device = entry.getValue();
            List<ChenCameraShotLog> shotLogs = shotMap.get(deviceSn);
            if (!CollectionUtils.isEmpty(shotLogs)) {
                for (ChenCameraShotLog shotLog : shotLogs) {
                    RealtimeShoot realtimeShoot = new RealtimeShoot();
                    realtimeShoot.setDeviceName(device.getDeviceName());
                    realtimeShoot.setDeviceSn(deviceSn);
                    realtimeShoot.setGetTime(shotLog.getReceiveTime() == null ? new Date() : shotLog.getReceiveTime());
                    realtimeShoot.setEvent("自动上传");
                    if (shotLog.getFileName() != null) {
                        String str = "http://118.121.206.5:1000/CameraFile/cdazh/" + shotLog.getFileName();
                        String path = fdfsService.updateFromIcc(str);
                        realtimeShoot.setPath(path);
                    } else continue;
                    realtimeShoot.setPlace(device.getDeviceAddress());
                    realtimeShoot.setLot(device.getLongitude());
                    realtimeShoot.setLat(device.getLatitude());
                    realtimeShoot.setSource(0);//0-陈博士
                    realtimeShoot.setOrgId(device.getFkOrgId());
                    realtimeShoots.add(realtimeShoot);
                }
            }
        }
        saveBatch(realtimeShoots);
    }

    /**
     * 动植物归档
     * @param realtimeShoot
     * @param dto
     * @param type
     */
    private void biologyFile(RealtimeShoot realtimeShoot, RealtimeShootFileDto dto, Integer type) {
        //图片视频归档存入生物附件表
        BiologyFile biologyFile = new BiologyFile();
        BeanUtils.copyProperties(dto, biologyFile);
        BeanUtils.copyProperties(realtimeShoot, biologyFile);
        biologyFile.setId(null);
        biologyFile.setDeviceCode(realtimeShoot.getDeviceSn());
        biologyFile.setShootingTime(realtimeShoot.getGetTime());
        biologyFile.setBiologyName(dto.getSpecies());
        biologyFile.setBiologyKingdom(dto.getKingdom());
        biologyFile.setType(type);
        biologyFile.setUrl(realtimeShoot.getPath());
        biologyFile.setCreator(UserUtil.getCurrentUser());
        biologyFileService.getBaseMapper().insert(biologyFile);
        //更新实时抓拍归档关联字段
        realtimeShoot.setFileType(0);
        realtimeShoot.setFileStatus(1);
        realtimeShoot.setFileRelation(biologyFile.getId().toString());
        updateById(realtimeShoot);
    }
}
